﻿using BW.Mes.WinForms.Production.ProductionCommon;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.Production.ProductionCommon.MainForm;

namespace BW.Mes.WinForms.Production.ProductionState
{
    public partial class ProduceLockForm : DevExpress.XtraEditors.XtraForm
    {
        // 存储选中的ID列表
        private List<long> _selectedIds;


        public ProduceLockForm()
        {
            InitializeComponent();
        }
        // 带参数的构造函数，接收选中的ID列表
        public ProduceLockForm(List<long> selectedIds)
        {
            InitializeComponent();
            _selectedIds = selectedIds;

            // 显示选中的记录数量
            this.Text = $"锁定确认 - 已选择{selectedIds.Count}条记录";
        }

        /// <summary>
        /// 确认锁定按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AffLock_Click(object sender, EventArgs e)
        {
            // 获取锁定原因
            string lockReason = this.richTextBox1.Text.Trim();

            // 验证锁定原因是否为空
            if (string.IsNullOrEmpty(lockReason))
            {
                XtraMessageBox.Show("请输入锁定原因", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.richTextBox1.Focus();
                return;
            }
            bool allSuccess = true;
            StringBuilder errorMessages = new StringBuilder();
            int successCount = 0;

            // 逐个处理每个选中的ID
            foreach (long id in _selectedIds)
            {
                // 构建锁定API URL，包含ID和锁定原因
                string lockUrl = $"{ProduceConst.Update_TRUE}/{id}/{Uri.EscapeDataString(lockReason)}";

                // 发送PUT请求，不需要请求体
                var responseJson = await ProduceHttpClientHelper.RequestUrl(
                    ProduceRequestType.put,
                    lockUrl);

                // 反序列化响应
                var lockResponse = JsonConvert.DeserializeObject<ProduceApiResult<bool>>(responseJson);

                if (lockResponse != null && lockResponse.Success)
                {
                    successCount++;
                }
                else
                {
                    allSuccess = false;
                    string errorMsg = lockResponse?.Message ?? "未知错误";
                    errorMessages.AppendLine($"ID {id} 锁定失败: {errorMsg}");
                }
            }

            if (allSuccess)
            {
                XtraMessageBox.Show("锁定成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 查找并刷新所有打开的ProduceFalseForm窗体
                foreach (Form form in Application.OpenForms)
                {
                    if (form is ProduceFalseForm falseForm)
                    {
                        await falseForm.LoadData();
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else if (successCount > 0)
            {
                XtraMessageBox.Show($"成功锁定 {successCount} 条记录，{_selectedIds.Count - successCount} 条记录失败:\n{errorMessages}",
                    "部分成功", MessageBoxButtons.OK, MessageBoxIcon.Warning);


                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                XtraMessageBox.Show($"所有记录锁定失败:\n{errorMessages}",
                    "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Reset_Click(object sender, EventArgs e)
        {
            // 设置对话框结果为取消
            this.DialogResult = DialogResult.Cancel;
            // 关闭窗口
            this.Close();
        }
    }
}